package com.example.hackotontest.communication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.hackotontest.R;

public class ScrumMasterCommunicationActivity extends Activity {

	private TextView messageReceivedFromClient;

	// default ip
	public static String ScrumMasterIP = "10.0.2.15";

	// designate a port
	public static final int SERVERPORT = 8080;

	private Handler handler = new Handler();

	private ServerSocket serverSocket;

	// client fields

	private EditText serversMessage;

	private Button sendMessage;

	private boolean connected;

	private String salahorIpAddress = "10.0.2.2";

	private Socket salahorListeningSocket;
	
	private static final int salahorPort = 8083;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scrum_master_communication);
		messageReceivedFromClient = (TextView) findViewById(R.id.client_received_message);

		// SERVERIP = getLocalIpAddress();

		// fe80::5054:ff:fe12:3456%eth0
		Thread fst = new Thread(new ServerThread());
		fst.start();

		// message from client
		serversMessage = (EditText) findViewById(R.id.server_message);
		sendMessage = (Button) findViewById(R.id.send_message_to_salahors);
		sendMessage.setOnClickListener(sendListener);

	}

	private OnClickListener sendListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// if (!connected) {
			// serverIpAddress = serverIp.getText().toString();
			// if (!serverIpAddress.equals("")) {
			Thread cThread = new Thread(new ClientThread());
			cThread.start();
			// }
			// }
		}
	};

	public class ClientThread implements Runnable {

		public void run() {
			try {

				if (!connected) {
					InetAddress serverAddr = InetAddress.getByName(salahorIpAddress);
					Log.d("ClientActivity", "SM: Connecting...");
					salahorListeningSocket = new Socket(serverAddr, salahorPort);
					connected = true;
				}
				// while (connected) {
				try {
					Log.d("ClientActivity", "SM: Sending command.");
					PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(salahorListeningSocket.getOutputStream())), true);
					// where you issue the commands
					out.println(serversMessage.getText().toString());
					Log.d("ClientActivity", "SM: Sent.");
				} catch (Exception e) {
					Log.e("ClientActivity", "S: Error", e);
				}
				// }
				// socket.close();
				// Log.d("ClientActivity", "C: Closed.");
			} catch (Exception e) {
				Log.e("ClientActivity", "C: Error", e);
				connected = false;
			}
		}
	}

	//server side
	public class ServerThread implements Runnable {

		public void run() {
			try {
				if (ScrumMasterIP != null) {
					handler.post(new Runnable() {
						@Override
						public void run() {
							messageReceivedFromClient.setText("Listening on IP: " + ScrumMasterIP);
						}
					});
					serverSocket = new ServerSocket(SERVERPORT);
					while (true) {
						// listen for incoming clients
						Socket client = serverSocket.accept();
						handler.post(new Runnable() {
							@Override
							public void run() {
								messageReceivedFromClient.setText("Connected.");
							}
						});

						try {
							BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
							String line = null;
							while ((line = in.readLine()) != null) {
								final String reportLine = line;
								Log.d("ServerActivity", line);
								handler.post(new Runnable() {
									@Override
									public void run() {
										messageReceivedFromClient.setText(reportLine);
										// do whatever you want to the front end
										// this is where you can be creative
									}
								});
							}
							break;
						} catch (Exception e) {
							handler.post(new Runnable() {
								@Override
								public void run() {
									messageReceivedFromClient.setText("Oops. Connection interrupted. Please reconnect your phones.");
								}
							});
							e.printStackTrace();
						}
					}
				} else {
					handler.post(new Runnable() {
						@Override
						public void run() {
							messageReceivedFromClient.setText("Couldn't detect internet connection.");
						}
					});
				}
			} catch (Exception e) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						messageReceivedFromClient.setText("Error");
					}
				});
				e.printStackTrace();
			}
		}
	}

	// gets the ip address of your phone's network
	private String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("ServerActivity", ex.toString());
		}

		Log.d("ServerActivity", ScrumMasterIP);
		return null;
	}

	@Override
	protected void onStop() {
		super.onStop();
		try {
			// make sure you close the socket upon exiting
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
